
Ext.namespace('sys.bzgsk');

	// 主页面
	sys.bzgsk.MailViewer = Ext.extend(Ext.Panel, {
				
		/**
		 * 设备电站树
		 */ 
		bdztree  : null,
		/**
		 * 左侧grid
		 */ 
		grid : null,
		
		detailGrid : null,
		
		/**
		 * 右侧详细信息
		 */ 
		detail : null,
		
		/**
		 * grid数据源
		 */
		storeGrid : null,
		
		detailStoreGrid : null,
		
		/**
		 * 菜单
		 */
		commandMenu : null,
		
		border : false,
		
	    /**
	     * 
	     */
		viewerConfig : undefined,
		
		/**
	     * 初始化
		 */
		initComponent : function() {
			var obj = this;
			
			this.addListener('render', function() {
				obj.startViewer.defer(1, obj);
			});

			this.layout	= 'fit';
			sys.bzgsk.MailViewer.superclass.initComponent.call(this);
		},
		
		/**
		 * 初始化顺序处理
		 */
		startViewer : function() {
			
			// 初始化页面
			this.renderViewer();
			// grid绑定菜单
			this.menuCreate();
			// 增加拖拽事件
			this.ddCreate();
		},
		
		/**
		 * 加载控件
		 */
		renderViewer : function() {
            var sbids;
			 var sbnames;
			var obj = this;
			 var expflag = false;
			var myloader = new Ext.tree.TreeLoader({
	        		url : 'equip!getBdzTree3.do?parentid=',
	        		listeners:{"beforeload":function(loader, node){ 
							var url = 'equip!getBdzTree3.do?parentid=' + node.id ;
							if (node.id.endWith('kv')||node.id=='0') {
								url += '&bdzid=' + document.getElementById("paramBdzid").value;
							}
							if (node.id.endWith('jgdy')) {
								url += '&bdzid=' + node.parentNode.id;
							}
							loader.url = url;//alert(url);
							//node.attributes["checked"]=false;
							//alert(node.attributes.checked);
							//node.ui.toggleCheck(false);
	        		}
	        		}
	   		 	});
			this.bdztree = new Ext.tree.TreePanel({
				
	            id:"win_bdz_tree",   
	            root : new Ext.tree.AsyncTreeNode({   
	        		id : "0", 
	        		draggable:false, 
	        		//singleClickExpand:true, //单选
	        		checked:false,//复选
	        		text : '设备'
				}),   
				loader:myloader,
		        useArrows:true,
		        autoScroll:true,
		        animate:true,
		        listeners:{'click': function(node) {
		        
		        	if( node.leaf== '1') {
		        		try {	//alert(node.leaf);
		        			obj.detail.getForm().findField('entity.sbid').setValue(node.id);
			                obj.detail.getForm().findField('entity.sbname').setValue(node.text);
			           //alert(node.parentNode.id);alert(node.parentNode.id.indexOf('jgsb'));
			            if (node.parentNode.id.indexOf('jgsb')!=-1) { //alert(node.parentNode.parentNode.id.replace('jgdy',''));
			            	obj.storeGrid.baseParams['searchBean.con2'] = node.parentNode.parentNode.id.replace('jgdy','');
							obj.detail.getForm().findField('entity.dydj').setValue(node.parentNode.parentNode.id.replace('jgdy',''));
			            	//  Ext.getCmp('con2').setValue(node.parentNode.parentNode.id.replace('jgdy',''));//alert(Ext.getCmp('con2').value);
			            }else{ //alert(node.parentNode.parentNode.parentNode.id.replace('jgdy',''));
			            	obj.storeGrid.baseParams['searchBean.con2'] = node.parentNode.parentNode.parentNode.id.replace('jgdy','');
							obj.detail.getForm().findField('entity.dydj').setValue(node.parentNode.parentNode.parentNode.id.replace('jgdy',''));
			            	// Ext.getCmp('con2').setValue(node.parentNode.parentNode.parentNode.id.replace('jgdy',''));
			            }
			       
					 obj.detail.getForm().findField('entity.sblx').setValue(node.attributes.qtip);
					 obj.detail.getForm().findField('entity.bzid').setValue(document.getElementById("paramBzid").value);
			            	obj.storeGrid.baseParams['searchBean.con3'] = node.attributes.qtip;
			            	obj.storeGrid.reload();
		        		} catch(e) {
		        			alert("error");
		        		}
		        	}
		        }}
			});
			this.bdztree.root.expand();
			/* 加载数据后操作 */
            	myloader.on("load", function(loader, node) { 
            			if (node.childNodes.length > 0  && expflag == false) {
            				for(var i =0;i<node.childNodes.length;i++) {
								if(!node.childNodes[i].text.endWith('站')) {
									node.childNodes[i].expand();
								} else {
									node.childNodes[i].expand();
									expflag = true;
									break;
								}
							}
            			}

                });
			//this.bdztree.expandAll();
			
			// checkbox触发事件
			 var checking = false;
			
		this.bdztree.on('checkchange', function(node,checked) { 
	
			if(checking){ 
				return false;
			}
				
			checking = true;
			// 选中的话
			if(node.ui.isChecked()){
				checkChildren(node,true);
				checkParent(node);
			   // getCheckSbID(node);
			// 没选中
			} else {
				checkChildren(node,false);
				uncheckParent(node);
			}
		
			checking = false;
		});
				
				
		// 子结点处理
		function checkChildren(node, checked)
		{
			//for(var i =0;i<node.childNodes.length;i++) {
			//	node.childNodes[i].ui.toggleCheck(checked);
			//	checkChildren(node.childNodes[i], checked);
			//}
	       node.attributes.checked = checked;
	       node.ui.toggleCheck(checked);
	       node.eachChild(function(child){
	         checkChildren(child,checked);
	       }); 
		};
	
		// 选中所有父结点
		function checkParent(node) {
	
			if(node.parentNode == null){
				return false;
			}
			node.parentNode.attributes.checked = true;
			node.parentNode.ui.toggleCheck(true);
			checkParent(node.parentNode);
		};
	
		// 取消所有父结点
		function uncheckParent(node) {
			if(node.parentNode == null) {
				return false;
			}
	
			var blCheck = true;
			for(var i =0;i<node.parentNode.childNodes.length;i++) {
				if(node.parentNode.childNodes[i].ui.isChecked()) {
					blCheck = false;
				}
			}
			if(blCheck) {
				node.parentNode.ui.toggleCheck(false);
				uncheckParent(node.parentNode);
			}
		};
		
			var sm = new Ext.grid.CheckboxSelectionModel();
			
			//----------------------------------------------------------------------
			//	列表数据源
			//----------------------------------------------------------------------
			this.storeGrid = new Ext.data.Store({
				proxy :new Ext.data.HttpProxy({
					url :'bzgsk!getBzgskList.do'
				}),
				reader :new Ext.data.JsonReader({
					root :'result',
					totalProperty :'totalCount',
					fields : ['id','bzid','bzname', 'dydj','dydjname','sblx','sblxname','zymc','bzgs']
				}),
			//	autoLoad:true,
				remoteSort :false,
				listeners:{'beforeload':function() {
					obj.storeGrid.baseParams['paramBzid'] = document.getElementById("paramBzid").value;
				}}
			});

			//----------------------------------------------------------------------
			//	加载列表
			//----------------------------------------------------------------------
			this.grid = new Ext.grid.GridPanel({
				id:"bzgsk_grid",
				store : obj.storeGrid,
				///frame:true,
				ddGroup:"gridDDGroup",
			//	enableDragDrop:true,
				stripeRows:true,
				cm: new Ext.grid.ColumnModel({
	        		defaults: {
	            		sortable: true
	        		},
	        		columns: [
	        			new Ext.grid.RowNumberer(),
	            		sm,
						{	id:'id',
							header :"序号",
							width :50,
							dataIndex :'id',
							sortable :true,
							hidden :true
						}, {
							header :"班组",
							width :50,
							dataIndex :'bzname',
							sortable :true,
							align:'center'
						}, {
							header :"电压等级",
							width :50,
							dataIndex :'dydjname',
							sortable :true,
							align:'center'
						},{
							header :"设备类型",
							width :50,
							dataIndex :'sblxname',
							sortable :true,
							align:'center'
						},{
							header :"标准作业名称",
							width :100,
							dataIndex :'zymc',
							sortable :true,
							align:'center'
						},{
							header :"标准工时",
							width :50,
							dataIndex :'bzgs',
							sortable :true,
							align:'center'
						}]
				}),
				sm : sm,
				loadMask : {
					msg :'载入中,请稍候...'
				},
				viewConfig:{
					forceFit:true
				},
				tbar :[
					/**{				       
		    			text : '电压等级：'
		    		} , {
                		xtype : 'combo',
                		width:100,
						name : 'con2',
						id:'con2',
						hiddenName : 'entity.dydj',
						store : new Ext.data.Store({
							proxy : new Ext.data.HttpProxy({
								url : 'dic!getDicJson.do?dic.itemType=DYDJ&emptyFlag=1'
							}),
							reader : new Ext.data.JsonReader({}, ['itemId', 'itemName']),
							autoLoad : true
						}),
						displayField : 'itemName',
						valueField : 'itemId',
						forceSelection : true,
						selectOnFocus : true,
						editable : false,
						triggerAction : 'all',
						mode : 'local',
						emptyText:'请选择'
					} , '-',{
						id :'noteList_query',
						text :'查询',
						cls:'x-btn-text-icon',
        				icon:contextpath + '/images/page_find.png',
			            handler:function() {
			            	//obj.storeGrid.baseParams['searchBean.con1'] = Ext.getCmp('con1').value;
			            	obj.storeGrid.baseParams['searchBean.con2'] = Ext.getCmp('con2').value;
			            	//obj.storeGrid.baseParams['searchBean.con3'] = Ext.getCmp('con3').value;
			            	obj.storeGrid.reload();
        				}
					},*/ /**btn_bzgsk_delete ? '' : '-',{
						id :'bzgsk_delete',
						text :'删除',
						cls:'x-btn-text-icon',
        				icon:contextpath + '/images/delete.gif',
        				hidden:btn_bzgsk_delete,
        				handler:function() {
        					obj.deleteBzgsk();
        				}
					},*/'-',{
						id : 'bzgzrw_checkout',
						text : '提取',
						cls:'x-btn-text-icon',
						icon:contextpath + '/images/add.gif',
						handler : function(){
							obj.checkout();
						}
					}
				],
				bbar : new Ext.PagingToolbar({
					store : obj.storeGrid,
					pageSize:100,
					displayInfo :true,
					displayMsg :'共 {2} 条',
					emptyMsg :"没有数据显示！"
				})
			});
			
			//----------------------------------------------------------------------
			//	加载详细信息
			//----------------------------------------------------------------------
			this.detail = new Ext.form.FormPanel({
				id : 'bzgsk_detail',
				//frame:true,
				bodyStyle  : 'padding: 10px; background-color: #DFE8F6',
				//autoScroll:true,
				//containerScroll:true,
				method :'POST',
				labelAlign:'right',
				tbar :[
					{
						id :'bzgsk_insert',
						text :'新建',
						cls:'x-btn-text-icon',
        				icon:contextpath + '/images/add.gif',
			            //hidden:btn_bzgsk_insert,
        				handler:function() {
        					obj.detail.getForm().reset();
        				}
					}, btn_bzgsk_save ? '' : '-',{
						text:'保存',
						icon:contextpath + "/images/save2.gif",
						//hidden:btn_bzgsk_save,
						handler: function() {
        					obj.submit();
        				}
					}, btn_bzgsk_save ? '' : '-',{
						text:'复选保存',
						icon:contextpath + "/images/save2.gif",
						//hidden:btn_bzgsk_save,
						handler: function() {
        					obj.saveSb();
        				}
					}
				],
		        items: [
	        	{
					fieldLabel :'班组',
					name :'bz',
					id : 'bz',
					xtype : 'combo',
					width:150,
					hiddenName : 'entity.bzid',
					store : new Ext.data.Store({
						proxy : new Ext.data.HttpProxy({
							url : 'bzgsk!getBz.do'
						}),
						reader : new Ext.data.JsonReader({}, ['id', 'organName']),
						autoLoad : true,
						listeners:{'load' : function() {
								var r = new Ext.data.Record({id:'', organName:''});
								Ext.getCmp('bz').store.insert(0,r);
							
						}}
					}),
					displayField : 'organName',
					valueField : 'id',
					forceSelection : true,
					selectOnFocus : true,
					editable : false,
					triggerAction : 'all',
					mode : 'local',
					allowBlank : false,
					emptyText:'请选择'
        		},  {
						fieldLabel :'电压等级',
						name :'dydj',
						id : 'dydj',
						xtype : 'combo',
						width:150,
						hiddenName : 'entity.dydj',
						store : new Ext.data.Store({
							proxy : new Ext.data.HttpProxy({
								url : 'dic!getDicJson.do?dic.itemType=DYDJ'
							}),
							reader : new Ext.data.JsonReader({}, ['itemId', 'itemName']),
							autoLoad : true,
							listeners:{'load' : function() {
									var r = new Ext.data.Record({itemId:'', itemName:''});
									Ext.getCmp('dydj').store.insert(0,r);
								
							}}
						}),
						displayField : 'itemName',
						valueField : 'itemId',
						forceSelection : true,
						selectOnFocus : true,
						editable : false,
						triggerAction : 'all',
						mode : 'local',
						allowBlank : false,
						emptyText:'请选择'
        		},{
						fieldLabel :'设备类型',
						name :'sblx',
						id : 'sblx',
						xtype : 'combo',
						width:150,
						hiddenName : 'entity.sblx',
						store : new Ext.data.Store({
							proxy : new Ext.data.HttpProxy({
								url : 'dic!getDicJson.do?dic.itemType=SBLX'
							}),
							reader : new Ext.data.JsonReader({}, ['itemId', 'itemName']),
							autoLoad : true,
							listeners:{'load' : function() {
									var r = new Ext.data.Record({itemId:'', itemName:''});
									Ext.getCmp('sblx').store.insert(0,r);
								
							}}
						}),
						displayField : 'itemName',
						valueField : 'itemId',
						forceSelection : true,
						selectOnFocus : true,
						editable : false,
						triggerAction : 'all',
						mode : 'local',
						allowBlank : false,
						emptyText:'请选择'        			
        		},{
            			xtype: 'textarea',
            			height:40,width: 150,
            			name: 'entity.gznr',
            			id : 'entity.gznr',
            			fieldLabel: '工作内容',
           				maxLength:100,
            			allowBlank:true,
						maxLength :100
        		},{
						xtype : 'textfield',
						fieldLabel :'标准工时',
        				width: 150,
            			name: 'entity.bzgs',
            			id : 'entity.bzgs',
						allowBlank : true,
						maxLength :50       		       		
        		},{
            			xtype: 'hidden',
            			name: 'entity.id',
            			id:'entity.id',
            			value:'0'
        		},{
            			xtype: 'hidden',
            			name: 'sblxid',
            			id:'sblxid'
        		},{
            			xtype: 'hidden',
            			name: 'bzid',
            			id:'bzid'
        		},{
            			xtype: 'hidden',
            			name: 'bid',
            			id:'bid'
        		},{
            			xtype: 'hidden',
            			name: 'entity.planid',
            			id:'entity.planid',
            			value:document.getElementById("paramPlanid").value
        		},{
            			xtype: 'textfield',
            			fieldLabel :'设备名称',
            			name: 'entity.sbname',
						//disabled : true,
						readOnly:true,
            			id:'entity.sbname'
        		}
				,{
            			xtype: 'hidden',
            			fieldLabel :'设备ID',
            			name: 'entity.sbid',
            			id:'entity.sbid'
        		},{
            			xtype: 'hidden',
            			fieldLabel :'工作任务单ID',
            			name: 'entity.gzrwdid',
            			id:'entity.gzrwdid',
            			value:document.getElementById("paramGzrwdid").value
        		},{
            			xtype: 'hidden',
            			fieldLabel :'设备IDS',
            			name: 'sbids',
            			id:'sbids'
            			
        		},{
            			xtype: 'hidden',
            			fieldLabel :'设备名称S',
            			name: 'sbnames',
            			id:'sbnames'
            			
        		}]
			});
			
			this.detailStoreGrid = new Ext.data.Store({
				proxy :new Ext.data.HttpProxy({
					url :'bzgzrwRw!getBzgzrwList.do'
				}),
				reader :new Ext.data.JsonReader({
					root :'result',
					totalProperty :'totalCount',
					fields : ['id','gznr', 'dydj','bzgs','bzname','sblxid','bid','sblx','sbname']
				}),
				autoLoad:true,
				remoteSort :false,
				listeners:{'beforeload':function() {
					obj.detailStoreGrid.baseParams['paramBzid'] = document.getElementById("paramBzid").value;
					obj.detailStoreGrid.baseParams['paramPlanid'] = document.getElementById("paramPlanid").value;
					obj.detailStoreGrid.baseParams['paramGzrwdid'] = document.getElementById("paramGzrwdid").value;
				}}
			});

			//----------------------------------------------------------------------
			//	加载列表
			//----------------------------------------------------------------------
			this.detailGrid = new Ext.grid.GridPanel({
				id:"bzgzrw_detailgrid",
				store : obj.detailStoreGrid,
				///frame:true,
				ddGroup:"gridDDGroup",
				enableDragDrop:true,
				stripeRows:true,
				cm: new Ext.grid.ColumnModel({
	        		defaults: {
	            		sortable: true
	        		},
	        		columns: [
	        			new Ext.grid.RowNumberer(),
						{	id:'id',
							header :"序号",
							width :50,
							dataIndex :'id',
							sortable :true,
							hidden :true
						}, {
							header :"班组",
							width :50,
							dataIndex :'bzname',
							sortable :true,
							align:'center'
						}, {
							header :"电压等级",
							width :50,
							dataIndex :'dydj',
							sortable :true,
							align:'center'
						},{
							header :"设备类型",
							width :50,
							dataIndex :'sblx',
							sortable :true,
							align:'center'
						},{
							header :"设备名称",
							width :50,
							dataIndex :'sbname',
							sortable :true,
							align:'center'
						},{
							header :"工作内容",
							width :100,
							dataIndex :'gznr',
							sortable :true,
							align:'center'
						},{
							header :"标准工时",
							width :50,
							dataIndex :'bzgs',
							sortable :true,
							align:'center'
						},{
							header :"设备类型id",
							width :50,
							dataIndex :'sblxid',
							hidden :true
						},{
							header :"班组id",
							width :50,
							dataIndex :'bid',
							hidden :true
						}]
				}),
				loadMask : {
					msg :'载入中,请稍候...'
				},
				viewConfig:{
					forceFit:true
				},
				tbar :[
					{
						id : 'bzgzrw_confirm',
						text : '回填任务',
						cls : 'x-btn-text-icon',
						icon:contextpath + '/images/add.gif',
						handler:function(){
							//obj.confirm2();
							obj.refresh();
						}
					}, btn_bzgzrw_delete ? '' : '-',{
						id :'bzgzrwdelete',
						text :'删除',
						cls:'x-btn-text-icon',
        				icon:contextpath + '/images/delete.gif',
        				hidden:btn_bzgzrw_delete,
        				handler:function() {
        					obj.deleteBzgzrw();
        				}
					}
				],
				bbar : new Ext.PagingToolbar({
					store : obj.storeGrid,
					pageSize:100,
					displayInfo :true,
					displayMsg :'共 {2} 条',
					emptyMsg :"没有数据显示！"
				}),
				listeners:{'rowdblclick':function(row) {
					obj.getDetail();
				}}
			});
			
			var viewer = new Ext.Panel({
			        layout:'border',
			        items:[{
			        	title:'标准工时库信息列表',
			            region:'west',
			            layout:'border',
			            width:800,
			            items:[{
			            	items: [obj.bdztree],
			            	region : 'west',
			            	layout:'fit',
			            	width:300,
			            	split:true,
			           		 collapsible:true
			            	},
			            	{
			            	items:[obj.grid],
			            	region:'center',
			            	layout:'fit'
			            }],
			            split:true,
			            collapsible:true,
			            //collapseMode: 'mini',
			            defaults:{autoScroll:true,border:false},
			            layoutConfig:{
			                animate:true
			            }
			        },{
			        	title:'班组工作任务',
			            region:'center',
			            layout:'border',
			            items:[{
			            	region:'north',
			            	layout:'fit',
			            	height:300,
			            	items:[obj.detail],
			            	 split:true
			            },{
			            	region:'center',
			            	layout:'fit',
			            	items:[obj.detailGrid]
			            }]
			        }]
			});
	
			this.add(viewer);

			if ((typeof this.layout) == "object") this.doLayout();

		},
		
		/**
		 * 菜单绑定
		 */
		menuCreate: function (){

			var obj = this;

			var actEdit = new Ext.Action({
				id			: 'menu_edit',
				text		: '修改',
				tooltip		: '修改当前变电站',
				iconCls		: 'icon_edit',
				handler		: function() { obj.getDetail()}
			});

			var actDelete = new Ext.Action({
				id			: 'menu_delete',
				text		: '删除',
				tooltip		: '删除当前变电站',
				iconCls		: 'icon_delete',
				hidden      : btn_bzgsk_delete,
				handler		: function() { obj.deleteBzgsk()}
			});
			
			obj.commandMenu = new Ext.menu.Menu({
				minWidth	: 160,
				items	: [
					actEdit, '-',
					actDelete
				]
			});
			
			obj.grid.on('rowcontextmenu',function (grid, rowIndex, e) {
      			e.preventDefault();
      			obj.grid.getSelectionModel().selectRow(rowIndex);
        		obj.commandMenu.showAt(e.getXY());   
			});
			
		},
		
		/**
		 * 拖拽
		 */
		ddCreate: function () {
			
			var obj = this;
			
			var formPanelDropTarget = new Ext.dd.DropTarget(obj.detail.body.dom, {
				ddGroup     : 'gridDDGroup',
				notifyEnter : function(ddSource, e, data) {
					obj.detail.body.stopFx();
					obj.detail.body.highlight();
				},
				notifyDrop  : function(ddSource, e, data){
					
					var record = ddSource.dragData.selections[0]['data'];
					
					for (var p in record) {
						try {
							obj.detail.getForm().findField("entity." + p).setValue(record[p]);
						} catch (e) {
							obj.detail.getForm().findField("entity.dydj").setRawValue(record[p]);
						}
					}
					return(true);
				}
			});
			
		},
        refresh: function() {
			window.opener.refresh();
			window.close();
				},
		/**
		 * 提交保存
		 */
		submit: function() {
			
			var obj = this;
			//alert(obj.detail.getForm().findField('entity.sbid').getValue());
			if (obj.detail.getForm().findField('entity.sbid').getValue()==null||obj.detail.getForm().findField('entity.sbid').getValue()=='') {
				Ext.MessageBox.alert("提示","请先选择设备");
				return;
			}
			// 验证有效性
        	if (!obj.detail.getForm().isValid()) {
        		return;
        	} 

			// 提交
			obj.detail.getForm().submit({
				waitMsg :'保存中...',
				url:'bzgzrwRw!save.do',
				success : function(form, action) {
					Ext.MessageBox.alert('提示', action.result.msg);
					if (Ext.isEmpty(action.result.rep)) {
						obj.detail.getForm().findField("entity.id").setValue(action.result.id);
						obj.detailStoreGrid.reload({
							callback:function(r, options, success) {
								obj.confirm2();
							}
						});
					}
				},
				failure : function(action) {
					Ext.MessageBox.alert('提示', '保存失败。');
				}
				
			});
			
		},
		
		/**
		 * 删除
		 */
		deleteBzgsk: function() {
			
			var obj = this;
			
			if (!obj.grid.getSelectionModel().hasSelection()) {
				Ext.MessageBox.alert("提示","请先选择要删除的记录");
				return;
			}
			
			var ids = obj.grid.getSelectionModel().getSelected()['data']['id'];
			
			Ext.MessageBox.confirm('提示', '确定要删除选中的【' + obj.grid.getSelectionModel().getSelected()['data']['zymc'] + '】记录吗？', function (btn) {
				
				if (btn == 'yes') {

					Ext.Ajax.request({
						method :'POST',
						url :'bzgsk!delete.do',
						params : {
							id :ids
						},
						success : function(response) {
							Ext.MessageBox.alert('提示', response.responseText);
							obj.grid.store.reload();
						},
						failure : function() {
							Ext.MessageBox.alert('提示', '删除失败！');
						}
					});
				}

			});
			
		},
		
		/**
		 * 获得详细信息
		 */
		getDetail: function() {

			var obj = this;
			
			var record = obj.detailGrid.getSelectionModel().getSelected()['data'];
			
			for (var p in record) {
				try {
					obj.detail.getForm().findField("entity." + p).setValue(record[p]);
				} catch (e) {
					if(p == 'bzname'){
						obj.detail.getForm().findField("entity.bzid").setValue(record[p]);
					}else if(p == 'bid'){
						obj.detail.getForm().findField("bid").setValue(record[p]);
					}else if(p == 'sblxid'){
						obj.detail.getForm().findField("sblxid").setValue(record[p]);
					}
					
				}
			}

		},
		// 过滤选择选中的复选框
	getCheckSbID:function (node) {

		if (node.ui.isChecked()) {
	
			if (node.leaf== '1') {
			
				// 设备ID
				document.getElementById("sbids").value = document.getElementById("sbids").value + node.id + ",";

				// 设备名
				document.getElementById("sbnames").value = document.getElementById("sbnames").value + node.text + ",";
			
			}
    		for (var i=0;i<node.childNodes.length;i++) {
    			this.getCheckSbID(node.childNodes[i]);
    		}
		}
	},
	 saveSb:function(){
	        var obj=this;
            document.getElementById("sbids").value="";
            document.getElementById("sbnames").value="";
 			this.getCheckSbID(this.bdztree.root.firstChild);
 			var sbid = document.getElementById("sbids").value;
 			var sbname = document.getElementById("sbnames").value;
 			
 			if (sbid.endWith(",")) {
 				document.getElementById("sbids").value = 
 					sbid.substring(0,sbid.length-1);
 			}
 			
 			if (sbname.endWith(",")) {
 				document.getElementById("sbnames").value = 
 					sbname.substring(0,sbname.length-1);
 			}
 			//alert("sbids=="+sbid);
 			//alert("sbnames=="+sbname);
			if (obj.detail.getForm().findField('sbnames').getValue()==null||obj.detail.getForm().findField('sbnames').getValue()=='') {
				Ext.MessageBox.alert("提示","请先选择同一电压等级，同一设备类型的设备");
				return;
			}
			// 验证有效性
        	if (!obj.detail.getForm().isValid()) {
        		return;
        	} 
 			var sbids=document.getElementById("sbids").value;
 			var sbnames=document.getElementById("sbnames").value;
 			var planid = document.getElementById("paramPlanid").value;
			var gzrwdid = document.getElementById("paramGzrwdid").value;
			// 提交
			obj.detail.getForm().submit({
				waitMsg :'保存中...',
				url:'bzgzrwRw!saveMulti.do',
				params : {
					id :sbids,
					sbnames:sbnames,
					paramPlanid:planid,
					paramGzrwdid:gzrwdid
					},
				success : function(form, action) {
					Ext.MessageBox.alert('提示', action.result.msg);
					if (Ext.isEmpty(action.result.rep)) {
						obj.detail.getForm().findField("entity.id").setValue(action.result.id);
						obj.detailStoreGrid.reload({
							callback:function(r, options, success) {
								obj.confirm2();
							}
						});
					}
				},
				failure : function(action) {
					Ext.MessageBox.alert('提示', '保存失败。');
				}
				
			});
 		},
		checkout: function(){
			var obj = this;
			var record;
			var ids = '';
			var planid = document.getElementById("paramPlanid").value;
			var sbid=document.getElementById("entity.sbid").value;
			var sbname=document.getElementById("entity.sbname").value;
			var gzrwdid = document.getElementById("paramGzrwdid").value;
			//alert(sbid);
			if (!obj.grid.getSelectionModel().hasSelection()) {
				Ext.MessageBox.alert("提示","请先选择要提取的记录");
				return;
			}
			if (obj.detail.getForm().findField('entity.sbid').getValue()==null||obj.detail.getForm().findField('entity.sbid').getValue()=='') {
				Ext.MessageBox.alert("提示","请先选择设备");
				return;
			}
			
			var records = obj.grid.getSelectionModel().getSelections();
			for(var i=0;i<records.length;i++){
				record = records[i]['data'];
				ids += record['id'] + ',';
			}
			
			if(ids != ''){
				ids = ids.substring(0,ids.length-1);
			}
			
			Ext.Ajax.request({
				method :'POST',
				url :'bzgzrwRw!checkout.do',
				params : {
					id :ids,
					paramPlanid:planid,
					paramSbid:sbid,
					paramSbname:sbname,
					paramGzrwdid:gzrwdid
				},
				success : function(response) {
					Ext.MessageBox.alert('提示', response.responseText);
					obj.detailStoreGrid.reload({
						callback:function(r, options, success) {
							obj.confirm2();
						}
					});
				},
				failure : function() {
					Ext.MessageBox.alert('提示', '提取失败！');
				}
			});			
			
		},
		
		confirm2 : function(){
			var obj = this;
			var record;
			var sbmc='';
			var gznrs = '';
			var bzid=0;
			var i=0;
			var store = obj.detailStoreGrid;
			var count = store.getCount();
			for(var i=0;i<count;i++){
				record = store.getAt(i)['data'];
				gznrs += record['sbname']+record['gznr'] + ';\n';
				bzid=record['bid'];
				//window.alert(record);
			}
			
			gznrs = gznrs.substr(0,gznrs.length-1);
			var len = parseInt(document.getElementById("paramBzlength").value);

			// 当前班任务
			for (var index=0; index<len;index++) {
				if (window.opener.document.frmM.elements["planbzList["+index+"].bzid"].value == document.getElementById("paramBzid").value) {
					window.opener.document.frmM.elements["planbzList["+index+"].gzrw"].value = gznrs;
					break;
				}
			}
			// 总任务
			var rw = '';
			for (var index=0; index<len;index++) {
				rw += window.opener.document.frmM.elements["planbzList["+index+"].gzrw"].value + "\n";
			}
			if (rw != '') {
				rw.substr(0,rw.length-2);
			}
			window.opener.document.frmM.elements["entity.workcontent"].value = rw;
	
		},
/**
		 * 删除任务
		 */
		deleteBzgzrw: function() {
			
			var obj = this;
			
			if (!obj.detailGrid.getSelectionModel().hasSelection()) {
				Ext.MessageBox.alert("提示","请先选择要删除的记录");
				return;
			}
			
			var ids = obj.detailGrid.getSelectionModel().getSelected()['data']['id'];
			
			Ext.MessageBox.confirm('提示', '确定要删除选中的【' + obj.detailGrid.getSelectionModel().getSelected()['data']['gznr'] + '】记录吗？', function (btn) {
				
				if (btn == 'yes') {

					Ext.Ajax.request({
						method :'POST',
						url :'bzgzrwRw!delete.do',
						params : {
							id :ids
						},
						success : function(response) {
							Ext.MessageBox.alert('提示', response.responseText);
							obj.detailStoreGrid.reload({
								callback:function(r, options, success) {
									obj.confirm2();
								}
							});
						},
						failure : function() {
							Ext.MessageBox.alert('提示', '删除失败！');
						}
					});
				}

			});
			
		}
	});
		